package sms_api

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/guid"
)

// SMSHandler SMS HTTP处理器
type SMSHandler struct {
	service *SMSService
	logger  *glog.Logger
}

// NewSMSHandler 创建SMS处理器
func NewSMSHandler(service *SMSService) *SMSHandler {
	return &SMSHandler{
		service: service,
		logger:  glog.New(),
	}
}

// RegisterRoutes 注册路由
func (h *SMSHandler) RegisterRoutes(server *ghttp.Server) {
	// API路由组
	api := server.Group("/api/v1/sms")

	// 中间件
	api.Middleware(h.corsMiddleware)
	api.Middleware(h.loggingMiddleware)
	api.Middleware(h.authMiddleware)
	api.Middleware(h.rateLimitMiddleware)

	// 短信发送相关
	api.POST("/send", h.SendSMS)
	api.POST("/batch", h.SendBatchSMS)
	api.GET("/query/:messageId", h.QuerySMS)
	api.POST("/query", h.QuerySMSByPost)

	// 系统相关
	api.GET("/health", h.HealthCheck)
	api.GET("/metrics", h.GetMetrics)
	api.GET("/providers", h.GetProviders)

	// 配置相关
	api.GET("/config", h.GetConfig)
	api.PUT("/config", h.UpdateConfig)
}

// SendSMS 发送单条短信
func (h *SMSHandler) SendSMS(r *ghttp.Request) {
	ctx := r.Context()

	// 解析请求
	req := &SendSMSRequest{}
	if err := r.Parse(req); err != nil {
		h.writeErrorResponse(r, http.StatusBadRequest, "INVALID_REQUEST", "请求参数解析失败: "+err.Error())
		return
	}

	// 生成消息ID（如果未提供）
	if req.MessageID == "" {
		req.MessageID = GenerateMessageID()
	}

	// 记录请求日志
	h.logger.Infof(ctx, "发送短信请求: MessageID=%s, Phone=%s, Provider=%s", 
		req.MessageID, h.maskPhone(req.Phone), req.Provider)

	// 发送短信
	resp, err := h.service.SendSMS(ctx, req)
	if err != nil {
		h.handleSMSError(r, err)
		return
	}

	// 返回成功响应
	h.writeSuccessResponse(r, resp)
}

// SendBatchSMS 批量发送短信
func (h *SMSHandler) SendBatchSMS(r *ghttp.Request) {
	ctx := r.Context()

	// 解析请求
	req := &BatchSMSRequest{}
	if err := r.Parse(req); err != nil {
		h.writeErrorResponse(r, http.StatusBadRequest, "INVALID_REQUEST", "请求参数解析失败: "+err.Error())
		return
	}

	// 生成批次ID（如果未提供）
	if req.BatchID == "" {
		req.BatchID = GenerateBatchID()
	}

	// 为每个请求生成消息ID
	for _, smsReq := range req.Requests {
		if smsReq.MessageID == "" {
			smsReq.MessageID = GenerateMessageID()
		}
	}

	// 记录请求日志
	h.logger.Infof(ctx, "批量发送短信请求: BatchID=%s, Count=%d, Provider=%s", 
		req.BatchID, len(req.Requests), req.Provider)

	// 批量发送短信
	resp, err := h.service.SendBatchSMS(ctx, req)
	if err != nil {
		h.handleSMSError(r, err)
		return
	}

	// 返回成功响应
	h.writeSuccessResponse(r, resp)
}

// QuerySMS 查询短信状态（GET方式）
func (h *SMSHandler) QuerySMS(r *ghttp.Request) {
	ctx := r.Context()
	messageID := r.Get("messageId").String()

	if messageID == "" {
		h.writeErrorResponse(r, http.StatusBadRequest, "MISSING_MESSAGE_ID", "消息ID不能为空")
		return
	}

	// 构建查询请求
	req := &QuerySMSRequest{
		MessageID:  messageID,
		ProviderID: r.Get("providerId").String(),
		Phone:      r.Get("phone").String(),
		Provider:   r.Get("provider").String(),
	}

	// 查询短信状态
	resp, err := h.service.QuerySMS(ctx, req)
	if err != nil {
		h.handleSMSError(r, err)
		return
	}

	// 返回成功响应
	h.writeSuccessResponse(r, resp)
}

// QuerySMSByPost 查询短信状态（POST方式）
func (h *SMSHandler) QuerySMSByPost(r *ghttp.Request) {
	ctx := r.Context()

	// 解析请求
	req := &QuerySMSRequest{}
	if err := r.Parse(req); err != nil {
		h.writeErrorResponse(r, http.StatusBadRequest, "INVALID_REQUEST", "请求参数解析失败: "+err.Error())
		return
	}

	// 查询短信状态
	resp, err := h.service.QuerySMS(ctx, req)
	if err != nil {
		h.handleSMSError(r, err)
		return
	}

	// 返回成功响应
	h.writeSuccessResponse(r, resp)
}

// HealthCheck 健康检查
func (h *SMSHandler) HealthCheck(r *ghttp.Request) {
	ctx := r.Context()

	// 执行健康检查
	resp := h.service.HealthCheck(ctx)

	// 根据状态设置HTTP状态码
	statusCode := http.StatusOK
	if resp.Status == "unhealthy" {
		statusCode = http.StatusServiceUnavailable
	} else if resp.Status == "degraded" {
		statusCode = http.StatusPartialContent
	}

	r.Response.WriteHeader(statusCode)
	h.writeSuccessResponse(r, resp)
}

// GetMetrics 获取指标
func (h *SMSHandler) GetMetrics(r *ghttp.Request) {
	// 获取指标
	resp := h.service.GetMetrics()

	// 返回成功响应
	h.writeSuccessResponse(r, resp)
}

// GetProviders 获取提供商列表
func (h *SMSHandler) GetProviders(r *ghttp.Request) {
	// 构建提供商信息
	providers := map[string]interface{}{
		"available": []string{"space_iot", "aliyun", "tencent", "huawei"},
		"default":   h.service.config.DefaultProvider,
		"enabled":   h.getEnabledProviders(),
	}

	// 返回成功响应
	h.writeSuccessResponse(r, providers)
}

// GetConfig 获取配置
func (h *SMSHandler) GetConfig(r *ghttp.Request) {
	// 返回脱敏后的配置
	config := h.getMaskedConfig()
	h.writeSuccessResponse(r, config)
}

// UpdateConfig 更新配置
func (h *SMSHandler) UpdateConfig(r *ghttp.Request) {
	ctx := r.Context()

	// 解析配置更新请求
	var updateReq map[string]interface{}
	if err := r.Parse(&updateReq); err != nil {
		h.writeErrorResponse(r, http.StatusBadRequest, "INVALID_REQUEST", "配置更新请求解析失败: "+err.Error())
		return
	}

	// 记录配置更新日志
	h.logger.Infof(ctx, "配置更新请求: %+v", updateReq)

	// TODO: 实现配置更新逻辑
	// 这里应该验证配置、更新服务配置、重新初始化提供商等

	// 返回成功响应
	h.writeSuccessResponse(r, map[string]interface{}{
		"message": "配置更新成功",
		"updated_at": time.Now(),
	})
}

// corsMiddleware CORS中间件
func (h *SMSHandler) corsMiddleware(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

// loggingMiddleware 日志中间件
func (h *SMSHandler) loggingMiddleware(r *ghttp.Request) {
	start := time.Now()
	path := r.URL.Path
	method := r.Method
	clientIP := r.GetClientIp()

	// 继续处理请求
	r.Middleware.Next()

	// 记录请求日志
	latency := time.Since(start)
	statusCode := r.Response.Status

	h.logger.Infof(r.Context(), "HTTP请求: %s %s %s %d %v", 
		clientIP, method, path, statusCode, latency)
}

// authMiddleware 认证中间件
func (h *SMSHandler) authMiddleware(r *ghttp.Request) {
	// 跳过健康检查和指标接口的认证
	if r.URL.Path == "/api/v1/sms/health" || r.URL.Path == "/api/v1/sms/metrics" {
		r.Middleware.Next()
		return
	}

	// 检查API密钥
	apiKey := r.Header.Get("X-API-Key")
	if apiKey == "" {
		apiKey = r.Get("api_key").String()
	}

	if apiKey == "" {
		h.writeErrorResponse(r, http.StatusUnauthorized, "MISSING_API_KEY", "API密钥不能为空")
		return
	}

	// TODO: 验证API密钥
	// 这里应该从配置或数据库中验证API密钥的有效性

	r.Middleware.Next()
}

// rateLimitMiddleware 速率限制中间件
func (h *SMSHandler) rateLimitMiddleware(r *ghttp.Request) {
	clientIP := r.GetClientIp()

	// TODO: 实现基于IP的速率限制
	// 这里应该检查客户端IP的请求频率

	_ = clientIP // 避免未使用变量警告
	r.Middleware.Next()
}

// handleSMSError 处理SMS错误
func (h *SMSHandler) handleSMSError(r *ghttp.Request, err error) {
	ctx := r.Context()

	// 记录错误日志
	h.logger.Errorf(ctx, "SMS操作失败: %v", err)

	// 根据错误类型返回相应的HTTP状态码和错误信息
	if smsErr, ok := err.(SMSError); ok {
		statusCode := h.getHTTPStatusFromSMSError(smsErr)
		h.writeErrorResponse(r, statusCode, smsErr.Code(), smsErr.Error())
		return
	}

	// 未知错误
	h.writeErrorResponse(r, http.StatusInternalServerError, "INTERNAL_ERROR", "内部服务器错误")
}

// getHTTPStatusFromSMSError 从SMS错误获取HTTP状态码
func (h *SMSHandler) getHTTPStatusFromSMSError(err SMSError) int {
	switch err.Code() {
	case "INVALID_PHONE", "INVALID_CONTENT", "INVALID_SIGN", "VALIDATION_ERROR":
		return http.StatusBadRequest
	case "RATE_LIMIT_EXCEEDED":
		return http.StatusTooManyRequests
	case "PROVIDER_NOT_FOUND", "INVALID_PROVIDER":
		return http.StatusBadRequest
	case "NETWORK_ERROR", "TIMEOUT":
		return http.StatusServiceUnavailable
	case "CIRCUIT_OPEN":
		return http.StatusServiceUnavailable
	case "INSUFFICIENT_BALANCE":
		return http.StatusPaymentRequired
	case "UNAUTHORIZED":
		return http.StatusUnauthorized
	case "FORBIDDEN":
		return http.StatusForbidden
	default:
		return http.StatusInternalServerError
	}
}

// writeSuccessResponse 写入成功响应
func (h *SMSHandler) writeSuccessResponse(r *ghttp.Request, data interface{}) {
	response := &CommonResponse{
		Code:      0,
		Message:   "success",
		Data:      data,
		Timestamp: time.Now(),
		RequestID: h.getRequestID(r),
	}

	r.Response.WriteJson(response)
}

// writeErrorResponse 写入错误响应
func (h *SMSHandler) writeErrorResponse(r *ghttp.Request, statusCode int, code, message string) {
	response := &ErrorResponse{
		Code:      code,
		Message:   message,
		Timestamp: time.Now(),
		RequestID: h.getRequestID(r),
		Path:      r.URL.Path,
	}

	r.Response.WriteHeader(statusCode)
	r.Response.WriteJson(response)
}

// getRequestID 获取请求ID
func (h *SMSHandler) getRequestID(r *ghttp.Request) string {
	// 从请求头获取请求ID
	if requestID := r.Header.Get("X-Request-ID"); requestID != "" {
		return requestID
	}

	// 生成新的请求ID
	return fmt.Sprintf("req_%d_%d", time.Now().UnixNano(), gconv.Int(r.GetClientIp()))
}

// maskPhone 脱敏手机号
func (h *SMSHandler) maskPhone(phone string) string {
	if len(phone) < 7 {
		return phone
	}

	// 保留前3位和后4位，中间用*替换
	if len(phone) == 11 {
		return phone[:3] + "****" + phone[7:]
	}

	// 国际号码处理
	if len(phone) > 7 {
		return phone[:3] + "****" + phone[len(phone)-4:]
	}

	return phone
}

// getEnabledProviders 获取启用的提供商列表
func (h *SMSHandler) getEnabledProviders() []string {
	var enabled []string

	if h.service.config.SpaceIoT.Enabled {
		enabled = append(enabled, "space_iot")
	}
	if h.service.config.Aliyun.Enabled {
		enabled = append(enabled, "aliyun")
	}
	if h.service.config.Tencent.Enabled {
		enabled = append(enabled, "tencent")
	}
	if h.service.config.Huawei.Enabled {
		enabled = append(enabled, "huawei")
	}

	return enabled
}

// getMaskedConfig 获取脱敏后的配置
func (h *SMSHandler) getMaskedConfig() map[string]interface{} {
	config := map[string]interface{}{
		"service": map[string]interface{}{
			"name":             h.service.config.Service.Name,
			"version":          h.service.config.Service.Version,
			"port":             h.service.config.Service.Port,
			"default_provider": h.service.config.DefaultProvider,
		},
		"retry": map[string]interface{}{
			"max_retries": h.service.config.Retry.MaxRetries,
			"base_delay":  h.service.config.Retry.BaseDelay.String(),
			"max_delay":   h.service.config.Retry.MaxDelay.String(),
			"multiplier":  h.service.config.Retry.Multiplier,
		},
		"rate_limit": map[string]interface{}{
			"requests_per_second": h.service.config.RateLimit.RequestsPerSecond,
			"burst_size":         h.service.config.RateLimit.BurstSize,
		},
		"batch": map[string]interface{}{
			"max_size":      h.service.config.Batch.MaxSize,
			"timeout":       h.service.config.Batch.Timeout.String(),
			"concurrent":    h.service.config.Batch.Concurrent,
		},
		"cache": map[string]interface{}{
			"enabled": h.service.config.Cache.Enabled,
			"ttl":     h.service.config.Cache.TTL.String(),
		},
		"providers": map[string]interface{}{
			"space_iot": map[string]interface{}{
				"enabled":  h.service.config.SpaceIoT.Enabled,
				"base_url": h.service.config.SpaceIoT.BaseURL,
				"sign":     h.maskString(h.service.config.SpaceIoT.Sign),
				"timeout":  h.service.config.SpaceIoT.Timeout.String(),
			},
			// TODO: 添加其他提供商的脱敏配置
		},
	}

	return config
}

// maskString 脱敏字符串
func (h *SMSHandler) maskString(s string) string {
	if len(s) <= 4 {
		return "****"
	}
	return s[:2] + "****" + s[len(s)-2:]
}

// StartHTTPServer 启动HTTP服务器
func StartHTTPServer(config *Config) error {
	// 创建SMS服务
	service, err := NewSMSService(config)
	if err != nil {
		return fmt.Errorf("创建SMS服务失败: %w", err)
	}

	// 创建HTTP处理器
	handler := NewSMSHandler(service)

	// 创建HTTP服务器
	server := g.Server()
	server.SetPort(config.Service.Port)
	server.SetServerRoot("./")

	// 注册路由
	handler.RegisterRoutes(server)

	// 添加全局中间件
	server.Use(func(r *ghttp.Request) {
		// 设置响应头
		r.Response.Header().Set("Content-Type", "application/json")
		r.Response.Header().Set("X-Service", "SMS-API")
		r.Response.Header().Set("X-Version", config.Service.Version)
		r.Middleware.Next()
	})

	// 启动服务器
	glog.Printf("SMS API服务启动，端口: %d", config.Service.Port)
	return server.Run()
}